package top.jle.spring.basic.fis;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.jle.jpa.basic.exception.BasicCustomException;
import top.jle.jpa.basic.exception.BasicExceptionCode;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Optional;

/**
 * @author jim.lee
 * @date 2022/7/28 11:42
 */
public interface EnumGetter {

     Logger LOGGER = LoggerFactory.getLogger(EnumGetter.class);
     /**
     * 根据枚举类指定属性和值获取枚举对象
     * @author jim.lee
     * @date 2022/7/28 14:29
     */
    static <T> T getByCode(Class<T> clazz,String field, String value){
        try {
            PropertyDescriptor pd = new PropertyDescriptor(field, clazz,"get"+ StringUtils.capitalize(field),null);
            Method method = pd.getReadMethod();
            Optional<T> any = Arrays.stream(clazz.getEnumConstants()).filter(e-> {
                try {
                    return method.invoke(e).equals(value);
                } catch (IllegalAccessException | InvocationTargetException ex) {
                    throw new BasicCustomException(BasicExceptionCode.SERVER_ERROR);
                }
            }).findAny();
            return any.orElse(null);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(),e);
        }
        return null;
    }

}
